package top.malaoshi.netdisk.filter;

import top.malaoshi.netdisk.vo.JsonCodeMsg;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.web.utils.Ajax;
import top.malaoshi.web.utils.ResponseUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//@WebFilter("/*")
public class F1AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {
    }

    private static List<String> notFilterPath=new ArrayList();
    static {
        notFilterPath.add("/js/*");//支持通配符*
        notFilterPath.add("/css/*");
        notFilterPath.add("/login.html");
        notFilterPath.add("/login");
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)arg0;
        HttpServletResponse resp=(HttpServletResponse)arg1;
        HttpSession session=req.getSession();

        //跨域会发送 OPTIONS 请求，直接放行
        if("OPTIONS".equals(req.getMethod())){
            fc.doFilter(arg0, arg1);
            return;
        }
        boolean b=isNotFilter(req);
        if(b) {
            fc.doFilter(arg0, arg1);
            return;
        }
        String uid=req.getHeader("uid");

//        System.out.println("AuthFilter:" + admin);
        if(uid!=null && !"".equals(uid)) {
            fc.doFilter(arg0, arg1);
        }else {
            if(Ajax.isAjax(req)){
                JsonResult result = new JsonResult(JsonCodeMsg.LOGIN_TIMEOUT.getCode(),"您未登录或登录超时，请重新登录！");
                ResponseUtils.sendJSON(resp,result);
            }else{

                String contextPath=req.getContextPath();
                resp.sendRedirect(contextPath+"/login.html?error=login_timeout");
            }

        }
    }
    private boolean isNotFilter(HttpServletRequest req) {
        String servletPath = req.getServletPath();
        for (String path:notFilterPath) {
//            if(servletPath.indexOf(path)>=0) {
//                return true;
//            }
            //将.替换成\.，表示普通的字符“.”，支持 *.html 格式
            path=path.replaceAll("\\.", "\\\\.");
            path=path.replaceAll("\\*", "\\.\\*");//将*替换成.*，然后进行正则表达式匹配
            if(servletPath.matches(path)){
                return true;
            }
        }
        return false;
    }
}
